package com.pentofab.payrollmanagement.ui.controller;

import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.UserAccountsDao;
import com.pentofab.payrollmanagement.dao.impl.UserAccountsDaoImpl;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;
import com.pentofab.payrollmanagement.database.impl.CreateDBConnection;
import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;


public class LoginController extends AbstractUIController
    implements Initializable {
	
	public static boolean isForgedLogin = false;
		@FXML
		Parent root;
		@FXML
	    private TextField answer;
	    @FXML
	    private Label answerLab;
	    @FXML
	    private Label conNewPasswordLab;
	    @FXML
	    private PasswordField confirmNewPassword;
	    @FXML	
	    private PasswordField newPassword;
	    @FXML
	    private Label newUseNameLab;
	    @FXML
	    private TextField newUserName;
	    @FXML
	    private Label newpasswordLab;
	    @FXML
	    private PasswordField passwordField;
	    @FXML
	    private ChoiceBox<String> question;
	    @FXML
	    private Label secQue;
	    @FXML
	    private TextField userName;
	    @FXML
	    private Button save;
	    @FXML
	    private Button cancel;
	    @FXML
	    private HBox buttonBox; 
	UserAccounts userAccounts = null;
	UserAccountsDao userAccountsDao = new UserAccountsDaoImpl();
	MainController mainController = null;
	
	boolean modify = false;
	boolean recover = false;
    

	public void login() {
		
		PayRollUtility.debug("Login event");
		String user = userName.getText();
		String password = passwordField.getText();
		
		if(password.contains("_TEMP")){
			
			isForgedLogin = true;
			password = password.replaceAll("_TEMP", "");
		}
		
		boolean istrail = false;
		String expDate = "";
		try{
			
		Connection conn = CreateDBConnection.cteateConnectionObj();
		
		String updateQuery= CreateDBConnection.query;
		System.out.println("updateQuery : "+updateQuery);
		if(!updateQuery.equals("")){
			
			PreparedStatement ps = conn.prepareStatement(updateQuery);
			ps.executeUpdate();
		}
		String query = "select status,expdate from APP_STATUS";
		PreparedStatement ps = conn.prepareStatement(query);
		ResultSet rs = ps.executeQuery();
		if(rs.next()){
			String status = rs.getString("status");
			if(status.equals("TRAIL")){
				
				istrail = true;
				
			}
			expDate = rs.getString("expdate");
			
			System.out.println("PayRollUtility.compareDateWithToday(expDate)" +PayRollUtility.compareDateWithToday(expDate));
			if(PayRollUtility.compareDateWithToday(expDate) < 0 ){
				
				showError("Application trail version expired. Please contact admin.");
				return;
			}
		}
		
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("=====================================");
			PayRollUtility.debug("Error while getting app satus");
		}
		try {

			if(istrail){
				
				showInfo("Currently application runnig ontrail Version,exp date is :"+expDate);
			}
			userAccounts = userAccountsDao.getUserAccountsByUserName(user);
			if(!password.equals(userAccounts.getPassword())){
				showError(UIMessages.WRONG_PASSWORD);
				return;
			}
			
			System.out.println("mainController ; "+mainController);
			if(mainController != null){
				
				mainController.refreshUI("Current user : "+user.toUpperCase());
			}
			if(!userAccounts.isActive()){
				 
				 throw new BusinessException(String.format(UIMessages.ACCOUNT_EXPIRED_CONTACT_ADMIN,userAccounts.getUsername()));
			 }
			PayrollApplicationFactory.getMainController().showScreen(MainController.COMPANIES_LIST_SCREEN, false ,userAccounts);
			
		} catch (Exception e) {
			
			e.printStackTrace();
			showError(e.getMessage());
			refreshUI(mainController);
			moveFocusToComp(userName);
		}

	}

	public void recover() {


		try {
			
			buttonBox.setVisible(false);
			userAccounts = userAccountsDao.getUserAccountsByUserName(userName.getText().trim());
			question.setVisible(true);
			secQue.setVisible(true);
			answerLab.setVisible(true);
			answer.setVisible(true);
			save.setVisible(true);
			cancel.setVisible(true);
			recover  = true;
			save.setText("View");
			if(userAccounts.getQuestion() == null || userAccounts.getQuestion().trim().equals("")){
				showError(UIMessages.SECURITY_QUESTION_NOT_SET);
				refreshUI(mainController);
				return;
			}
			question.getSelectionModel().select(userAccounts.getQuestion());
			
		} catch (BusinessException e) {
			showError(e.getMessage());
			refreshUI();
		}
	}
	
	public void change(){
		
		buttonBox.setVisible(false);
		modify = true;

		String user = userName.getText();
		String password = passwordField.getText().trim();
		save.setText("Modify");

		try {

			userAccounts = userAccountsDao.getUserAccountsByUserName(user);
			if(!password.equals(userAccounts.getPassword())){
//				showError(String.format(UIMessages.WRONG_PASSWORD,"5"));
				showError(UIMessages.WRONG_PASSWORD);
				refreshUI(mainController);
				moveFocusToComp(userName);	
				return;
			}
			if(!userAccounts.isActive()){
				 
				 throw new BusinessException(String.format(UIMessages.ACCOUNT_EXPIRED_CONTACT_ADMIN,userAccounts.getUsername()));
			 }
		} catch (BusinessException e) {
			e.printStackTrace();

			showError(e.getMessage());
			refreshUI(mainController);
			moveFocusToComp(userName);			
			return;
		}

		
		userName.setEditable(false);
		passwordField.setEditable(false);
		enableForModify(true);
		
		
	
	}
	public void save(){
		
		if(modify){
			
			String validationMsg = getValidationMsg();
			if(!validationMsg.equals("")){
				showError(validationMsg);
				moveFocusToComp(newUserName);
				return;
			}
			userAccounts.setUsername(newUserName.getText().trim());
			try{
				
				String oldusername = userName.getText().trim();
				String newuserName = newUserName.getText().trim();
			if(userAccounts.getPassword().equals(newPassword.getText().trim())){
				showError(UIMessages.LOGIN_DETAILS_SAME);
				return;
			}
			if(!oldusername.equals(newuserName) && userAccountsDao.getUserAccountsByUserName(newUserName.getText().trim()) != null){
				showError( newUserName.getText().trim()+" : "+UIMessages.USER_EXISTS);
				return;
			}
			}catch(Exception e){
				
			}
			userAccounts.setPassword(newPassword.getText().trim());
			userAccounts.setQuestion(question.getSelectionModel().getSelectedItem());
			userAccounts.setAnswer(answer.getText());
			
			try {
				
				userAccountsDao.modifyUserAccount(userAccounts,userName.getText().trim());
			} catch (Exception e) {
				showError(e.getMessage());
				return;
			}
			
			showInfo(String.format(UIMessages.SAVED_USER_ACCOUNT, newUserName.getText()));
		}

		if(recover){
			
			if(answer.getText().trim().equals("")){
				showError(UIMessages.ANSWER_EMPTY);
				moveFocusToComp(answer);
				return;
			}
			
			if(!answer.getText().trim().equals(userAccounts.getAnswer())){
				showError(UIMessages.ANSWER_NOT_MATCHING);
				moveFocusToComp(answer);
				return;
			}
			
			showInfo(String.format(UIMessages.PASSWORD_IS, userAccounts.getPassword()));
		}
		
		refreshUI(mainController);
		recover =false;
		modify= false;
	}
	
	
    @Override 
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

    }

    @Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {
		return UIMessages.UITitles.LOGIN_FORM;
	}

	@Override
	public void refreshUI(Object... args) {
		
		if(args != null && args.length > 0 && args[0] instanceof MainController){
			mainController = (MainController) args[0];
		}else{
			mainController = null;
		}
		userAccounts = null;
		userName.clear();
		passwordField.clear();
		moveFocusToComp(userName);
		enableForModify(false);
		question.getSelectionModel().clearSelection();
		userName.setEditable(true);
		passwordField.setEditable(true);
		buttonBox.setVisible(true);
		recover = false;
		modify = false;
		answer.clear();
		newUserName.clear();
		newPassword.clear();
		confirmNewPassword.clear();
		question.getSelectionModel().clearSelection();
	}
	
	public void refreshUI(){
		refreshUI(mainController);
	}
	private void enableForModify(boolean value){
		
		newUseNameLab.setVisible(value);
		newUserName.setVisible(value);
		newpasswordLab.setVisible(value);
		newPassword.setVisible(value);
		conNewPasswordLab.setVisible(value);
		confirmNewPassword.setVisible(value);
		save.setVisible(value);
		question.setVisible(value);
		secQue.setVisible(value);
		answerLab.setVisible(value);
		answer.setVisible(value);
		buttonBox.setVisible(!value);
		cancel.setVisible(value);
	}
	
	private String getValidationMsg(){
		
		if(newUserName.getText().trim().equals("")){
			return UIMessages.USER_NAME_EMPTY;
		}
		
		if(newUserName.getText().trim().length() < 5){
			return UIMessages.USER_NAME_LENGHT;
		}
		
		if(newPassword.getText().trim().equals("")){
			return UIMessages.PASSWORD_FIELD_LENGHT;
		}
		
		if(newUserName.getText().trim().length() <6){
			return UIMessages.PASSWORD_FIELD_LENGHT;
		}
		
		if(confirmNewPassword.getText().trim().equals("")){
			return UIMessages.PASSWORD_RETYPE_FIELD_EMPTY;
		}
		
		
		if(!confirmNewPassword.getText().trim().equals(newPassword.getText().trim())){
			return UIMessages.PASSWORDS_NOT_EQUAL;
		}
		
		if(question.getSelectionModel().getSelectedIndex() < 0){
			return UIMessages.SELECT_QUESTION;
		}
		if(answer.getText().trim().equals("")){
			return UIMessages.ANSWER_EMPTY;
		}
		return "";
	}

}

